const express = require('express');
const puppeteer = require('puppeteer');
const { Cluster } = require('puppeteer-cluster');
const app = express();
const port = 3000;

app.use(express.json());

// 创建一个Puppeteer连接池
async function startServer() {
  const cluster = await Cluster.launch({
    concurrency: Cluster.CONCURRENCY_CONTEXT,
    maxConcurrency: 16,
    puppeteerOptions: { headless: "new", args: ["--no-sandbox"] }
  });

  // 使用路由参数来接收 URL
  app.get('/generate-pdf', async (req, res) => {
    const { url } = req.query;

    if (!url) {
      return res.status(400).send('URL parameter is required.');
    }

    try {
      await cluster.task(async ({ page, data: url }) => {
        await page.setCacheEnabled(true);
        page.on('console', consoleMessage => console.log(consoleMessage.text()));
        page.on('pageerror', pageError => console.error(pageError.message));
        await page.goto(url,{ timeout: 90000 });

        try {
          await page.waitForFunction(() => {
            // 在此处编写您的逻辑，检查页面上的Vue.js数据是否已加载完成
            // 例如，检查某个DOM元素是否已经存在或包含所需的数据
            return document.querySelector('.ant-spin-spinning') == null;
          }, { timeout: 60000 });
          console.log(`Element with id "page_completed" is now loaded. URL: ${url}`);
        } catch (error) {
          console.error(`Timeout waiting for element with id "page_completed". URL: ${url}`);
        }
        // await page.evaluate(() => {
        //   return new Promise((resolve) => {
        //     const timeout = setTimeout(() => {
        //       observer.disconnect(); // 正确使用observer变量来停止观察
        //       resolve(); // 即使条件未满足也解决Promise
        //     }, 30000); // 设置30秒超时

        //     const observer = new MutationObserver((mutations) => {
        //       const element = document.querySelector('.ant-spin-spinning');
        //       if (element == null) {
        //         clearTimeout(timeout); // 清除超时计时器
        //         resolve();
        //         observer.disconnect(); // 正确停止观察
        //       }
        //     });

        //     observer.observe(document, {
        //       childList: true,
        //       subtree: true
        //     });
        //   });
        // });

        // await page.waitForTimeout(10000);

        const pdfBuffer = await page.pdf({
          format: 'A4',
          printBackground: true,
          margin: {
            top: '10mm',
            bottom: '10mm',
            left: '10mm',
            right: '10mm'
          }
        });
        console.log(`pdfBuffer is completed`);
        res.setHeader('Content-Disposition', 'attachment; filename=generated.pdf');
        res.setHeader('Content-Type', 'application/pdf');
        res.send(pdfBuffer);
      });

      cluster.queue(url);

    } catch (error) {
      console.error('Error generating PDF:', error);
      res.status(500).send('Error generating PDF.');
    }
  });

  app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
  });
}

startServer();
